(function () {

    var $modal = function (id) {
        this.instance = $('#' + id);
        this.data = {};
        this.json = {};
        this.callBack = function (resp) {};
    };

    $modal.prototype = {

        showModal: function(){
            this.instance.modal('show');
        },

        hideModal: function(){
            this.instance.modal('hide');
        },

        clearData: function(){
            this.data = {};
        },

        getData: function(){
            return this.data;
        },

        resetForm: function(){
            this.instance.find('input[name=id]').val('');
            this.instance.find('form')[0].reset();
        },

        setForm: function(json){
            this.instance.find('form').formEdit(json);
            return true;
        },

        setValue: function(key, value){
            this.data[key] = (typeof value == "undefined") ? $("#" + key).val() : value;
            return this;
        },

        setJson: function(json){
            this.json = json;
            return this;
        },

        getValue: function(key){
            return $("#" + key).val();
        },

        collectData: function(){
            this.data = this.instance.find('form').serializeJson();
        },

        setData: function(json){
            if(json != null && json != undefined && json != {}){
                for(var p in json){
                    this.data[p] = json[p];
                }
            }
        },

        setCallBack: function (callBack) {
            this.callBack = callBack;
            return this;
        },

        submit: function(url){
            var that = this;
            that.collectData();
            that.setData(this.json);

            console.log(that.data);

            $.post(url, that.data, function(resp){
                if(resp.code == '200'){
                    that.resetForm();
                    that.hideModal();
                    that.callBack(resp);
                }else{
                    layer.alert(resp.msg);
                }
            });
        }
    };

    window.Modal = $modal;

} ());



